import camera
import network
import socket
import time

# WiFi配置（与主控一致）
ssid = "LAPTOP-D3RPTUAA 6358"
password = "19234949992.ch"
ip = "192.168.137.129"    # 固定IP，与HTML中视频地址一致
gateway = "192.168.137.1"
subnet = "255.255.255.0"
dns = "8.8.8.8"

def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.ifconfig((ip, subnet, gateway, dns))  # 配置固定IP
    if not wlan.isconnected():
        print('连接WiFi...')
        wlan.connect(ssid, password)
        timeout = 0
        while not wlan.isconnected() and timeout < 10:
            print(f'等待连接...({timeout})')
            timeout += 1
            time.sleep(1)
    return wlan.isconnected()

def init_camera():
    try:
        camera.init(
            framesize=camera.FRAME_VGA,  # 640x480
            format=camera.JPEG,          # 输出JPEG格式
            quality=10                   # 图像质量（1-63，越小质量越高）
        )
        print("摄像头初始化成功")
        return True
    except Exception as e:
        print(f"摄像头初始化失败: {e}")
        return False

def start_mjpeg_stream():
    """手动实现MJPEG流服务"""
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(('0.0.0.0', 80))
    server.listen(1)
    print("MJPEG流服务器启动，等待连接...")
    
    boundary = b"esp32cam_boundary"  # MJPEG边界标识
    headers = b"HTTP/1.1 200 OK\r\n"
    headers += b"Content-Type: multipart/x-mixed-replace; boundary=" + boundary + b"\r\n\r\n"
    
    while True:
        try:
            conn, addr = server.accept()
            print(f"客户端连接: {addr}")
            req = conn.recv(1024)
            if b"/webcam" in req:  # 匹配视频流请求
                conn.send(headers)
                while True:
                    # 捕获图像（JPEG格式）
                    buf = camera.capture()  # 返回JPEG字节数据
                    # 封装MJPEG帧
                    frame = b"--" + boundary + b"\r\n"
                    frame += b"Content-Type: image/jpeg\r\n"
                    frame += b"Content-Length: " + str(len(buf)).encode() + b"\r\n\r\n"
                    frame += buf + b"\r\n"
                    conn.send(frame)
                    time.sleep(0.1)  # 控制帧率（10帧/秒）
        except Exception as e:
            print(f"连接异常: {e}")
            if 'conn' in locals():
                conn.close()

if __name__ == "__main__":
    if connect_wifi() and init_camera():
        start_mjpeg_stream()
    else:
        print("初始化失败，5秒后重试...")
        time.sleep(5)
        # 可添加重试逻辑